const jwt = require("jsonwebtoken");
const { dbName } = require("../modal/db.config");
const {calcLimit} = require("../modal/sqlLimit.config");
const SECRET = dbName;
class UserService {
  constructor(app) {
    this.app = app;
  }
  async findById(id) {
    return await this.app.mysql.getOne("users", { id });
  }
  async findByPhone(phone) {
    return await this.app.mysql.getOne("users", { phone });
  }
  async find(data) {
    return await this.app.mysql.getOne("users", { ...data });
  }


  async getList(data) {
    return await this.app.mysql.select("users", {
      where: data.where || {},
      like: data.like || {}, // like 条件
      orders: [{ field: "id", direction: "desc" }], // 排序方式
      offset: data.page
          ? calcLimit(Number(data.page), Number(data.pageSize)).page
          : null, // 数据偏移量
      limit: data.page
          ? calcLimit(Number(data.page), Number(data.pageSize)).pageSize
          : null, // 返回数据量
    });
  }

  async getCount(data) {
    return await this.app.mysql.count("users", {
      where: data.where || {},
      like: data.like || {}, // like 条件
    });
  }


  async createUser(data) {
    return await this.app.mysql.insert("users", { ...data });
  }
  async update(data, condition) {
    return await this.app.mysql.update("users", data, condition);
  }
  async delete(id) {
    return await this.app.mysql.delete("users", { id });
  }

  async decodeToken() {
    const { app } = this;
    // 1. 获取请求头 authorization 属性，值为 token
    const token = app.headers.authorization?.replace("Bearer ", ""); // 拿到token
    // 2. 用 app.jwt.verify(token， app.config.jwt.secret)，解析出 token 的值
    return jwt.verify(token, SECRET);
  }
}

module.exports = UserService;
